import 'package:environmental_les_app/common/net/net.dart';
import 'package:environmental_les_app/common/routes/route_names.dart';
import 'package:environmental_les_app/common/utils/sp_util.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/utils/string_util.dart';

class LoginController extends GetxController {
  LoginController();

  final phoneController = TextEditingController();
  final pwdController = TextEditingController();
  final FocusNode phoneFocusNode = FocusNode();
  final FocusNode pwdFocusNode = FocusNode();
  final vCodeController = TextEditingController();
  final FocusNode vCodeFocusNode = FocusNode();
  bool isPwdLogin = true; // 是否密码登录

  void onChangeLoginType() {
    isPwdLogin = !isPwdLogin;
    update(["login"]);
  }

  void onForgetPwd() {}

  /// 校验登录信息
  bool _checkInfo() {
    var phone = getControllerString(phoneController);
    var pwd = getControllerString(pwdController);
    var code = getControllerString(vCodeController);

    if (phone.isEmpty) {
      ToastUtil.showToast("请输入手机号");
      return false;
    }

    if (phone.length < 11 || !isMobile(phone)) {
      ToastUtil.showToast("请输入正确的手机号");
      return false;
    }

    if (isPwdLogin && pwd.isEmpty) {
      ToastUtil.showToast("请输入登录密码");
      return false;
    }

    if (!isPwdLogin && (code.isEmpty || code.length != 6)) {
      ToastUtil.showToast("请输入正确验证码");
      return false;
    }

    return true;
  }

  _initData() {
    update(["login"]);
  }

  void onLogin() {
    KeyBoardUtils.hideKeyboard();
    if (_checkInfo()) {
      isPwdLogin ? pwdLogin() : fastLogin();
    }
  }

  void pwdLogin() {
    var phone = getControllerString(phoneController);
    var pwd = EncryptUtil.encodeMd5(getControllerString(pwdController));
    var params = {"password": pwd, "username": phone};
    NetUtils.post(ServiceApi.login, data: params, successCallback: (res) {
      saveToken(res);
      onLoginCallback();
    }, errorCallback: (code, msg) {
      ToastUtil.showToast(msg);
    });
  }

  /// 快速登录
  void fastLogin() {
    var phone = getControllerString(phoneController);
    var vCode = getControllerString(vCodeController);
    var params = {"captcha": vCode, "username": phone};
    NetUtils.post(ServiceApi.login, data: params, successCallback: (res) {
      saveToken(res);
      onLoginCallback();
    });
  }

  void onLoginCallback() {
    Get.offAllNamed(AppRoutes.mainPage);
  }

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
